#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "InetAddr.hpp"
#include "Logger.hpp"
#include <functional>

using callback = std::function<void(int sockfd,std::string message,InetAddr addr)>;

class Server
{
public:
    Server(uint16_t port)
        : _port(port)
    {
    }
    void Init()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket创建失败";
            exit(1);
        }
        LOG(LogLevel::INFO) << "socket创建成功";
        InetAddr local(_port);
        int n = bind(_sockfd, local.Addr(), local.Length());
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind失败" << _sockfd;
            exit(2);
        }
        LOG(LogLevel::INFO) << "bind成功" << _sockfd;
    }
    void Start()
    {
        while (true)
        {
            char buffer[1024];
            buffer[0] = 0;
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int n = recvfrom(_sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&peer, &len);
            if (n > 0)
            {
                buffer[n] = 0;
                InetAddr clientaddr(peer);
                LOG(LogLevel::DEBUG) << "get a client info # "
                                     << clientaddr.Ip() << "-" << clientaddr.Port() << ": "
                                     << buffer;
                std::string message = buffer;
                _cb(_sockfd,message,clientaddr);
            }
        }
    }
    ~Server() {}

private:
    int _sockfd;
    int _port; // 端口号
    callback _cb;
};